package com.bosicloud.cmb.ibp.commom.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;

/**
 * @author Jack Peng / ziliang.peng@bosicloud.com
 */
public class IOUtils {

    public static ByteBuffer getAsByteArray(URL url) throws IOException {
        URLConnection connection = url.openConnection();

        InputStream in = connection.getInputStream();

        int contentLength = connection.getContentLength();

        ByteArrayOutputStream tmpOut;
        if (contentLength != -1) {
            tmpOut = new ByteArrayOutputStream(contentLength);
        } else {
            tmpOut = new ByteArrayOutputStream(16384);
        }

        byte[] buf = new byte[512];
        while (true) {
            int len = in.read(buf);
            if (len == -1) {
                break;
            }
            tmpOut.write(buf, 0, len);
        }
        in.close();
        tmpOut.close();

        byte[] array = tmpOut.toByteArray();

        //FileOutputStream fos = new FileOutputStream("C:\\abc.pdf");
        //fos.write(array);
        //fos.close();

        return ByteBuffer.wrap(array);
    }

}
